package com.flashflexpro.tanksinbattle.menuscene {
import com.flashflexpro.tanksinbattle.loader.LoadModuleEvent;
import com.flashflexpro.tanksinbattle.menuscene.dto.MenuDto;
import com.flashflexpro.tanksinbattle.menuscene.dto.MenuSceneDto;
import com.flashflexpro.tanksinbattle.scene.AScene;
import com.flashflexpro.tanksinbattle.scene.dto.Dto;

import flash.display.MovieClip;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.net.NetConnection;
import flash.net.Responder;
import flash.text.TextField;

/**
 * the logic is in 2 places:
 * 1) here the code
 * 2) the menu scene dto passed in,
 * The dto should be generated in editor originally and passed in here from previous module,
 * but all possibilities should be defined in here.
 *
 * the view is in the Flash swf
 * todo: how to trigger switching between menus from menuitem interaction?
 *       how to define and expose all the possibilities to editor?
 *       good news is that this is inside this module
 *
 */
[Event(name="moduleReady", type="flash.events.Event")]
public class MenuScene extends MovieClip implements AScene{

    private var _tmpTxt:TextField;


    public function get tmpTxt():TextField {
        return _tmpTxt;
    }

    public function set tmpTxt(value:TextField):void {
        _tmpTxt = value;
    }

    private var _sceneDto:MenuSceneDto;
    public function MenuScene(sceneDto:MenuSceneDto) {
        _sceneDto = sceneDto;

        addEventListener(MenuItem.SWITCH_TO_MENU, onSwitchToMenu);
        addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
    }

    private var _from:Dto;
    public function get fromDto():Dto {
        return _from;
    }

    public function start(passIn:Dto):void {
        _from = passIn;
        dispatchEvent(new LoadModuleEvent(LoadModuleEvent.MODULE_READY));
    }


    private function onAddedToStage(event:Event):void {
        switchToMenu( _sceneDto.menus[ 0 ] as MenuDto );
    }

    private var _currentMenu:Menu;
    private function onSwitchToMenu(event:Event):void {
        var item:MenuItem = event.target as MenuItem;
        switchToMenu( item.menuItemDto.switchToMenu );
    }

    private function switchToMenu(menuItemDto:MenuDto):void {
        var lastIndex:int = numChildren - 1;
        while( lastIndex > 0 ){
            if( getChildAt( lastIndex ) is Menu ){
                removeChildAt( lastIndex );
            }
            lastIndex --;
        }
        _currentMenu = Menu(addChild(new Menu( menuItemDto ) ) );
    }

    private function onBattleModuleReady(event:Event):void {
        ( event.target as EventDispatcher ).removeEventListener(Event.COMPLETE, onBattleModuleReady);
    }

    public function destroy():void {
        removeEventListener(MenuItem.SWITCH_TO_MENU, onSwitchToMenu);
        removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
    }

}
}